package com.app.bimo.commonbusiness.network;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.SharedPreUtils;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Random;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

public class RetrofitServiceManager {

    private static RetrofitServiceManager mInstance;
    private HashMap<String, RetrofitUtil> services;

    public static RetrofitServiceManager getInstance() {
        if (mInstance == null) {
            synchronized (RetrofitServiceManager.class) {
                if (mInstance == null) {
                    mInstance = new RetrofitServiceManager();
                }
            }
        }
        return mInstance;
    }

    private RetrofitServiceManager() {
        services = new HashMap<>();
    }

    public void addRetrofitService(Context context, String serviceName, String baseUrl) {
        if (services.containsKey(serviceName)) {
            return;
        }
        RetrofitUtil service = new RetrofitUtil(getHost(context, baseUrl));
        services.put(serviceName, service);
    }

    public <T> T createRetrofit(String serviceName, Class<T> serviceClass) {
        if (services.containsKey(serviceName)) {
            RetrofitUtil util = services.get(serviceName);
            return util.createService(serviceClass);
        }
        return null;
    }


    /**
     * 给所有的Retrofit实例添加相同的头部
     *
     * @param key
     * @param value
     */
    public void addAllHead(String key, String value) {
        for (String temp : services.keySet()) {
            RetrofitUtil util = services.get(temp);
            if (util != null) {
                util.addHead(key, value);
                Log.e("ok", value);
            }
        }
    }

    /**
     * 给所有的Retrofit实例移除的头部
     *
     * @param key
     */
    public void removeAllHead(String key) {
        for (String temp : services.keySet()) {
            RetrofitUtil util = services.get(temp);
            if (util != null) {
                util.removeHead(key);
            }
        }
    }


    /**
     * 给指定的Retrofit实例移除头部
     *
     * @param serviceName
     * @param key
     */
    public void removeHead(String serviceName, String key) {
        RetrofitUtil util = services.get(serviceName);
        if (util != null) {
            util.removeHead(key);
        }
    }

    /**
     * 给指定的Retrofit实例添加头部
     *
     * @param serviceName
     * @param key
     * @param value
     */
    public void addHead(String serviceName, String key, String value) {
        RetrofitUtil util = services.get(serviceName);
        if (util != null) {
            util.addHead(key, value);
        }
    }

    public void refreshHost(Context context) {
        for (String temp : services.keySet()) {
            RetrofitUtil util = services.get(temp);
            if (util != null) {
                util.refreshBuild(getHost(context, util.getHost()));
            }
        }
    }

    public String getHost(Context context, String baseHost) {
        String json = SharedPreUtils.getInstance(context).getString(Constant.APiUrl);
        /**从本地存储中获取的地址**/
        if (DataUtil.isEmpty(json)) {
            return baseHost;
        }
        BaseUrlResultData data = new Gson().fromJson(json, BaseUrlResultData.class);
        if (data == null) {
            return baseHost;
        }
        if (data.getApi().size() == 0) {
            return baseHost;
        }
        if (!DataUtil.isEmpty(data.getUsingApi())) {
            return data.getUsingApi();
        }
        String str = check(context, data);
        return str;
    }

    private String check(Context context, BaseUrlResultData data) {
        Random r = new Random();
        int index = data.getApi().size();
        if (index > 1) {
            index--;
        }
        int position = r.nextInt(index);
        if (data.getDisabledApi().contains(data.getApi().get(position))) {
            check(context, data);
        }
        data.setUsingApi(data.getApi().get(position));
        setHost(context, data, false);
        return data.getApi().get(position);
    }

    public String getHtmlHost(Context context, String baseHost) {
        String json = SharedPreUtils.getInstance(context).getString(Constant.APiUrl);
        /**从本地存储中获取的地址**/
        if (DataUtil.isEmpty(json)) {
            return baseHost;
        }
        BaseUrlResultData data = new Gson().fromJson(json, BaseUrlResultData.class);
        if (data == null) {
            return baseHost;
        }
        Random r = new Random();
        int end;
        int position;
        if (data.getH5().size() > 0) {
            end = data.getH5().size() - 1;
            if (end > 0) {
                position = r.nextInt(end);
            } else {
                position = 0;
            }
            return data.getH5().get(position);
        } else {
            return "";
        }

    }


    public void setHost(Context context, BaseUrlResultData host, boolean isFirst) {
        /**存储获取到的地址***/
        if (host == null) {
            SharedPreUtils.getInstance(context).putString(Constant.APiUrl, "");
        }
        SharedPreUtils.getInstance(context).putString(Constant.APiUrl, new Gson().toJson(host));
        if (isFirst) {
            Intent intent = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
            intent.putExtra("json", "api=" + "");
//            //发送本地广播
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        }
        RetrofitServiceManager.getInstance().refreshHost(context);
    }

    public BaseUrlResultData getHostData(Context context) {
        /**存储获取到的地址***/
        String json = SharedPreUtils.getInstance(context).getString(Constant.APiUrl);
        return new Gson().fromJson(json, BaseUrlResultData.class);
    }

}
